package com.tueye.web.controller.publishtopic;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.tueye.base.util.Page;
import com.tueye.cache.TuEyeCache;
import com.tueye.entity.TopicType;
import com.tueye.entity.Topics;
import com.tueye.entity.user.Flowers;
import com.tueye.entity.user.User;
import com.tueye.service.IKeyWordService;
import com.tueye.service.ITopicService;
import com.tueye.service.exception.TuEyeServiceException;
import com.tueye.service.usermanager.IRegisterService;
import com.tueye.utils.DateUtils;
import com.tueye.utils.TuEyeConstant;
import com.tueye.utils.UUIDGenerator;

import freemarker.template.TemplateException;



/**
 *  Title: UploadFileController.java
 *  Description: upload the imagess.
 * @author yuyue
 * @version 0.5 (for test)
 * 
 */
@SuppressWarnings("unchecked")
@Controller
public class TopicManagerController {

	Log log = LogFactory.getLog(TopicManagerController.class);
	String file_spe = File.separator;
	@Autowired
	@Qualifier("topicService")
	ITopicService topicService;

	@Autowired
	@Qualifier("tueyecache")
	TuEyeCache tueyecache;
	
	@Autowired
	@Qualifier("keyWordService")
	IKeyWordService keyWordService;
	
	@Autowired
	@Qualifier("registerService")
	private IRegisterService registerService;
	
	@RequestMapping("/topiclist.do") 
	public void  TopicList(HttpServletRequest request, HttpServletResponse response) throws TuEyeServiceException, IOException, TemplateException{
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
  
		String qtype=request.getParameter("qtype");//获取 查询的类型
		//String sortorder=request.getParameter("sortorder");//获取 查询的类型
		//String sortorder = desc;
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.Topics ");
		//if(StringUtils.isNotEmpty(query)) hql.append(" where "+query);
		hql.append("where (  topic_change =1 ");
		if(StringUtils.isNotEmpty(query)) {
			hql.append(" and "+qtype+" ='"+query+"'");
		}
		hql.append(" )  ");
	//	if(StringUtils.isNotEmpty(qtype))hql.append("   order   by "+qtype);
		hql.append("order by topic_uploadDate desc ");
	//	if(StringUtils.isNotEmpty(sortorder))hql.append("   "+sortorder);
		System.out.println("##########hql:"+hql.toString());
		 
		Page page = topicService.pagedQueryByHQL(hql.toString(), new Integer(pageString), new Integer(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", page.getTotalCount());
		String jsonStr = getJsonString((ArrayList)page.getResult(),pageInfo);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		System.out.println(jsonStr);
		response.getWriter().println(jsonStr);
		
		
		
	}
	/**
	 * commend in the near future 
	 * @author hxw
	 * @param request
	 * @param response
	 * @throws TuEyeServiceException
	 * @throws IOException
	 * @throws TemplateException
	 */
	@RequestMapping("/topicNearFuture.do") 
	public void  TopicNearFuture(HttpServletRequest request, HttpServletResponse response) throws TuEyeServiceException, IOException, TemplateException{
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
  
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.Topics ");
		hql.append("where (  topic_change =2 ");
		//if(StringUtils.isNotEmpty(query)) hql.append(" where "+query);
		if(StringUtils.isNotEmpty(query)) {
			hql.append(" and "+qtype+" ='"+query+"')");
		}
		hql.append(" ) ");
		if(StringUtils.isNotEmpty(qtype)) {
			hql.append("   order   by "+qtype);
		}
		if(StringUtils.isNotEmpty(sortorder)) {
			hql.append("   "+sortorder);
		}
		System.out.println("##########hql:"+hql.toString());
		 
		Page page = topicService.pagedQueryByHQL(hql.toString(), new Integer(pageString), new Integer(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", page.getTotalCount());
		String jsonStr = getJsonString((ArrayList)page.getResult(),pageInfo);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
		
		
	}
	
	@RequestMapping("/showtopic.do") 
	public String  ShowTopic(HttpServletRequest request, HttpServletResponse response) throws Exception{
	    String topic_id = request.getParameter("id");
	    Topics topic = this.topicService.getTopicById(topic_id);
	    request.setAttribute("topic", topic);
	    return "pages/admin/topicmanager/final";
	}
	
	/**
	 * 点击作品静态页后，更新防问次数
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/topicclick.do") 
	public void TopicClick(HttpServletRequest request, HttpServletResponse response) throws Exception{
	    String topic_id = request.getParameter("topicid");
	    tueyecache.addClickForTopic(topic_id);
	    //如果session中有user 把页面上边的导航改一下
	    User user =  (User) request.getSession().getAttribute(TuEyeConstant.TUEYE_USER);
	    response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
        if(user  != null){
        	   String data = "{username:'"+user.getByname()+"',userid:'"+user.getId()+"'}";
        		response.getWriter().print(data);
        }else{
        	response.getWriter().print("333");
        }
	  
	   
	}
	
	/**
	 * 修改页面的用户是否登录
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/useriflogin.do") 
	public void useriflogin(HttpServletRequest request, HttpServletResponse response) throws Exception{
	   
	    User user =  (User) request.getSession().getAttribute(TuEyeConstant.TUEYE_USER);
	    
	    response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
        if(user  != null){
        	    String data = "{username:'"+user.getByname()+"',userid:'"+user.getId()+"'}";
        		response.getWriter().print(data);
        }else{
        	 String useremail = request.getParameter("useremail");
        	 if(useremail != null){
        		 //去数据库拿出
        		List l =  registerService.getUserByemail(useremail);
        		if(l.size() > 0){
        			user = (User) l.get(0);
        			request.getSession().setAttribute(TuEyeConstant.TUEYE_USER, user);
        			String data = "{username:'"+user.getByname()+"',userid:'"+user.getId()+"'}";
            		response.getWriter().print(data);
        		} else{response.getWriter().print("333");}
        	 }else{
        	response.getWriter().print("333");}
        }
	  
	   
	}
	@RequestMapping("/initTopic.do") 
	public ModelAndView initDetail(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String topic_id = request.getParameter("id");
		Topics topic = new Topics();
		topic = this.topicService.getTopicById(topic_id);
		request.setAttribute("topic", topic);
		request.setAttribute("types", tueyecache.allTopicTypes()); 
		request.setAttribute("keywords", this.keyWordService.getKeyWordList());
		ModelAndView mav = new ModelAndView("/pages/admin/topicmanager/addTopic");
		return mav;
	}
	@RequestMapping("/updateTopic.do") 
	public String updateTopic(HttpServletRequest request, HttpServletResponse response)  {
		try{
		String topic_id = request.getParameter("id");
		String topic_title = request.getParameter("topic_title");
		String topic_overview = request.getParameter("topic_overview");
		String topic_type = request.getParameter("topic_type");
	//	String topic_change = request.getParameter("topic_change");
		String topic_from = request.getParameter("topic_from");
		String keywords = request.getParameter("keywords");
		String topic_author = request.getParameter("topic_author");
		String topic_description = request.getParameter("topic_description");
		Topics topic = new Topics();
		topic = this.topicService.getTopicById(topic_id);
		topic.setTopic_title(topic_title);
		topic.setTopic_author(topic_author);
		topic.setTopic_overview(topic_overview);
		//topic.setTopic_change(Integer.valueOf(topic_change));
		TopicType topicType = topic.getTopic_type();
		if(topicType!=null && !topicType.getId().equals(topic_type))
		{
			
			TopicType ty = topicService.getTopicTypeById(topic_type);
			topic.setTopic_type(ty);
			//将原topic的文件全部移动现topic下．
			File f  = new File(TuEyeConstant.PROJECTPATH +File.separator +topicType.getType_enlish_name() +File.separator + topic.getTopic_code());
			// 
			File fileab = new File(TuEyeConstant.PROJECTPATH+File.separator + ty.getType_enlish_name() + File.separator +topic.getTopic_code());
			if(!fileab.isDirectory()){
				fileab.mkdir();
			}
			
			File[] files = f.listFiles();
			for(File ff : files){
				File newFile = new File(TuEyeConstant.PROJECTPATH + File.separator +ty.getType_enlish_name() +File.separator + topic.getTopic_code() + File.separator +ff.getName());
				ff.renameTo(newFile);
			}
			f.delete();
			
		}
		 
		
		topic.setTopic_description(topic_description);
		topic.setKeywords(keywords);
		topic.setTopic_from(topic_from);
		this.topicService.saveTopics(topic);
		response.getWriter().print("true");
		}catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}
	
	
	private String getJsonString(List list, Map pageInfo) {
           
		List mapList = new ArrayList();   
		for (int i = 0; i < list.size(); i++) {
			Topics topic = (Topics) list.get(i);
			Map cellMap = new HashMap();
			 
		//	cellMap.put("adinfos", "<a href='adinfos.jsp?id="+adsite.getId()+"'>查看</a>");
    		cellMap.put("cell", new Object[]{ 
    				topic.getId(),
    				 i+1,
    				topic.getTopic_title(),
    				StringUtils.isEmpty(topic.getTopic_author())?getUserIdByTopic(topic):topic.getTopic_author(),
    				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",topic.getSys_time()),
    				tueyecache.getclickNumByTopicId(topic.getId())==null?"0":tueyecache.getclickNumByTopicId(topic.getId()),
    				StringUtils.isEmpty(topic.getTopic_from())?"TUEYE":topic.getTopic_from(),
    				topic.getTopic_type().getType_name(),
    				topic.getKeywords(),
    				"<a href=\"../../../showtopic.do?id="+topic.getId()+"\" target='_blank'>查看</a>",
    				"<a href=\"javascript:issuance('"+topic.getId()+"' )\" onclick=\"#\" >发布</a>"
    		});
    		  
    				mapList.add(cellMap);
    				
		}
		
    	pageInfo.put("rows", mapList);
    	com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(pageInfo);
    	return object.toString();
	}
	 private String getUserIdByTopic(Topics topic){
		 if(topicService.getUserByTopic(topic).getByname() != null) {
			return  topicService.getUserByTopic(topic).getByname();
		} else {
			return  topicService.getUserByTopic(topic).getEmail();
		}
		 }
	@RequestMapping("/deletetopic.do") 
	public void delete (HttpServletRequest request, HttpServletResponse response){
		
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			topicService.delTopic(id);
			response.getWriter().print("true");
		} catch (Exception e) {
			log.error("#####出错了"+e.getMessage());
			
		}
	}
	
	@RequestMapping("/deletePic.do") 
	public void deletePic (HttpServletRequest request, HttpServletResponse response){
		try {
			//request.setCharacterEncoding("UTF-8");
			String picpath = TuEyeConstant.PROJECT_TOPIC_PATH+request.getParameter("picpath");
			//picpath = picpath.substring(picpath.indexOf("/"), picpath.length());
			String id = request.getParameter("id");
			topicService.delePic(id, picpath);
		}catch (Exception e) {
			log.error(e.getMessage());
		}
	}
	
	@RequestMapping("/sendFlower.do") 
	public void sendFlower (HttpServletRequest request, HttpServletResponse response) throws  Exception{
		 String topicId = request.getParameter("topicid");
		 String flowerTypeId = request.getParameter("flowid");
		 Topics topic = topicService.getTopicById(topicId);
		 int flowtypeId = 0;
		 if(flowerTypeId != null){
			 flowtypeId = new Integer(flowerTypeId);
		 }
		 Flowers ff ;
		 
		 if(topic.getFlowers() == null || topic.getFlowers().size() == 0){
			 ff = new Flowers();
			 ff.setId(UUIDGenerator.getUUID());
		 }else {
			 ff = topic.getFlowers().get(0);
		 }
		 if(flowtypeId == 1){
			 ff.setFlowersNum(getFlowNum(ff.getFlowersNum()));
		 }else if(flowtypeId == 2){
			 ff.setZanNum(getFlowNum(ff.getZanNum()));
		 }else if(flowtypeId == 3){
			 ff.setCaiNum(getFlowNum(ff.getCaiNum()));
		 }else if(flowtypeId == 4){
			 ff.setKouNum(getFlowNum(ff.getKouNum()));
		 }else if(flowtypeId == 5){
			 ff.setPaiNum(getFlowNum(ff.getPaiNum()));
		 }
		
		 ff.setSys_time(DateUtils.getCurrentDate());
		 
		 ff.setTopics(topic);
		 topicService.saveFlower(ff);
		 response.getWriter().print("true");
		 
	}
	
	public int getFlowNum(Integer num){
		if (num == null){
			return 1;
		}else{
			return num+1;
		}
	
	}
	
	
	
	
}
